package scatter.common.rest.config;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import scatter.common.rest.concurrency.CustomExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 通用的线程池配置类
 * </p>
 *
 * @author yangwei
 * @since 2021-06-13 21:14
 */
public class CommonExecutorsConfig {

	/**
	 * 翻译线程池
	 * @param beanFactory
	 * @return
	 */
	@Bean(name = "transTaskExecutor", destroyMethod = "shutdown")
	public ExecutorService transTaskExecutor(BeanFactory beanFactory, MeterRegistry meterRegistry) {
		return CustomExecutors.newExecutorService(beanFactory,
				"transTaskExecutor",
				1,
				100,
				100,
				new LinkedBlockingQueue<>(100),
				// 如果拒绝自己执行
				new ThreadPoolExecutor.CallerRunsPolicy(),
				true,meterRegistry);
	}

	/**
	 * 通用数据库查询线程池
	 * @param beanFactory
	 * @return
	 */
	@Bean(name = "commonDbTaskExecutor", destroyMethod = "shutdown")
	public ExecutorService commonDbTaskExecutor(BeanFactory beanFactory, MeterRegistry meterRegistry) {
		return CustomExecutors.newExecutorService(beanFactory,
				"commonDbTaskExecutor",
				5,
				100,
				1000,
				new LinkedBlockingQueue<>(1000),
				// 如果拒绝自己执行
				new ThreadPoolExecutor.CallerRunsPolicy(),
				true,meterRegistry);
	}

	/**
	 * 异步槽位线程池
	 * @param beanFactory
	 * @return
	 */
	@Bean(name = "asynSlotTaskExecutor", destroyMethod = "shutdown")
	public ExecutorService asynSlotTaskExecutor(BeanFactory beanFactory, MeterRegistry meterRegistry) {
		return CustomExecutors.newExecutorService(beanFactory,
				"asynSlotTaskExecutor",
				5,
				100,
				1000,
				new LinkedBlockingQueue<>(1000),
				// 如果拒绝自己执行
				new ThreadPoolExecutor.CallerRunsPolicy(),
				true,meterRegistry);
	}
}
